home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: alisa.org!wjjr
- From: wjjr@alisa.org (John J. Rushford)
- Subject: Re: Unix Pipes and descrpitors
- X-Newsreader: TIN [version 1.2 PL2]
- Organization: My place on the Front Range.
- Message-ID: <DonJst.HHq@alisa.org>
- References: <Pine.ULT.3.91.960319174425.8464A-100000@midir>
- Date: Fri, 22 Mar 1996 04:43:41 GMT
-
- Colm Connolly (colmconn@midir.ucd.ie) wrote:
- : Having created a pipe, how do I access the file descriptors created by the
- : pipe system call after I call exec? I'd be grateful if someone could help
- : me with this.
-
- : Colm Connolly.
-
- : PS Manuals or books for that matter haven't helped much with this!!
-
- A pipe is half duplex which means you can read from it or write to it. Keeping
- this in mind, you may want to create two pipes if you need to read from and
- write to the forked child where you do the exec().
-
- Anyway, say you are going to read stdout of the child from the parent and you
- want to write to stdin of the child from the parent then:
-
- int fda[2], fdb[2], pid, status;
-
- /*
- * full duplex pipeline.
- */
- if (pipe (fda) < 0 || pipe (fdb) < 0) {
- exit (1);
- }
-
- if ((pid = fork ()) < 0) {
- exit (2);
- }
-
- if (pid == 0) { /* in the child */
-
- /* set up read half of pipeline on stdin */
- close (0);
- dup (fda[0]);
- close (fda[0]);
- close (fda[1]);
-
- /* set up write half of pipeline on stdout */
- close (1);
- dup (fdb[1]);
- close (fdb[1]);
- close (fdb[0]);
-
- /*
- * the pipe file descriptors are now stdin and stdout of the
- * child process so, exec () your program.
- */
-
- exec();
- }
-
- if (pid > 0) { /* in the parent */
-
- /* set up parents half of the pipeline. */
- close (fda[0]);
- close (fdb[1]);
-
- /*
- * fda[1] is used to write to stdin of the child.
- * fdb[0] is used to read from stdout of the child.
- * use fdopen() on the above two file descriptors if
- * you want to use stdio on these descriptors otherwise.
- * use read() or write().
- */
-
- wait (&status);
- }
-
- Of couse this was implemented on a Unix system. Hope this is usefule.
-
- regards
- --
- John J. Rushford
- Westminster, Colorado___/\_/\_
- wjjr@alisa.org (alisa.org is powered by FreeBSD)
-
-